import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:fsharing/core/models/me.dart';
import 'package:fsharing/core/models/store_apply_query.dart';
import 'package:fsharing/core/models/user_total.dart';
import 'package:fsharing/core/viewmodels/app_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/mine_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/reg_new_qr_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/main.dart';
import 'package:fsharing/ui/pages/mine/invited_page.dart';
import 'package:fsharing/ui/pages/mine/order/order_page.dart';
import 'package:fsharing/ui/widgets/mine_func_button.dart';
import 'package:fsharing/ui/widgets/mine_order_button.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';

class MinePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    AppLoginModel appLoginModel = Provider.of(context);

    // 未登录
    if (!appLoginModel.isLogin) {
      return Scaffold(
        body: Center(
          child: RaisedButton(
            onPressed: () => Navigator.of(context).pushNamed('/login'),
            child: Text('点击登录'),
          ),
        ),
      );
    }

    // 已登录
    return ChangeNotifierProvider(
      create: (context) => MineModel(
        Provider.of(context, listen: false),
        Provider.of(context, listen: false),
      ),
      child: Consumer<MineModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return Center(
                child: CircularProgressIndicator(),
              );
            case ViewState.error:
              return Center(
                child: Text(model.errorMessage),
              );
            case ViewState.success:
              // 更新店铺列表
              AppStoreModel appStoreModel = Provider.of(context, listen: false);
              appStoreModel.updateStoreList(
                model.userTotal.storeOptions,
                model.userTotal.unmanagedStoreIds,
              );
              return MultiProvider(
                providers: [
                  Provider.value(value: model.me),
                  Provider.value(value: model.userTotal),
                ],
                child: _SuccessWidget(),
              );
            default:
              return Container();
          }
        },
      ),
    );
  }
}

class _SuccessWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Me me = Provider.of(context, listen: false);
    return Scaffold(
      appBar: AppBar(
        title: Text('我的'),
        actions: <Widget>[
          IconButton(
            icon: Image.asset('assets/images/mine/ic_invite.png', width: 20),
            onPressed: () => Navigator.of(context).pushNamed(
              '/invited',
              arguments: InvitedPageArgs(me, me.userIdInClient, me.userIdInClient),
            ),
          ),
          IconButton(
            icon: Icon(Icons.settings),
            /*Image.asset('assets/images/mine/ic_invite.png', width: 20)*/
            onPressed: () => Navigator.of(context).pushNamed('/setting', arguments: me),
          ),
        ],
        backgroundColor: Colors.black38,
      ),
      body: Theme(
        data: lightTheme(),
        child: Material(
          child: CustomScrollView(
            slivers: <Widget>[
              _HeaderWidget(),
              _BottomTitleWidget(),
              _BottomFuncWidget(),
            ],
          ),
        ),
      ),
    );
  }
}

class _HeaderWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SliverToBoxAdapter(
      child: Theme(
        data: dartTheme(),
        child: Material(
          color: Colors.transparent,
          child: Stack(
            alignment: Alignment.bottomCenter,
            children: <Widget>[
              Container(
                decoration: BoxDecoration(
                  color: Color(0xFF565862),
                ),
                height: 212,
                margin: EdgeInsets.only(bottom: 23),
              ),
              Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage('assets/images/mine/img_header.png'),
                    fit: BoxFit.fill,
                  ),
                ),
                height: 200,
                margin: EdgeInsets.symmetric(horizontal: 18),
              ),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 36),
                height: 212 - 6.0,
                margin: EdgeInsets.only(bottom: 23),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    _HeaderItemOneWidget(),
                    _HeaderItemTwoWidget(),
                    _HeaderItemThreeWidget(),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _HeaderItemOneWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Me me = Provider.of(context, listen: false);
    return InkWell(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: <Widget>[
          CircleAvatar(
            radius: 35,
            backgroundImage: CachedNetworkImageProvider(me?.avatar ?? ''),
          ),
          Expanded(
            child: Container(
              margin: EdgeInsets.symmetric(horizontal: 6),
              child: Text(
                '${me.username}  ',
                style: TextStyle(
                  color: Theme.of(context).accentColor,
                  fontSize: 25,
                  fontWeight: FontWeight.bold,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ),
          Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/mine/img_auth.png'),
                fit: BoxFit.fill,
              ),
            ),
            padding: EdgeInsets.symmetric(vertical: 4, horizontal: 7),
            child: Text(
              me.realName != null ? '实名认证' : '未实名认证',
              style: TextStyle(fontSize: 12),
            ),
          )
        ],
      ),
      onTap: () {
        _onUserClicked(context);
      },
    );
  }

  /// 点击用户信息
  void _onUserClicked(BuildContext context) async {
    Me me = Provider.of(context, listen: false);
    await Navigator.of(context).pushNamed('/user', arguments: me);

    // 点了用户信息页面，返回后刷新一下数据。
    MineModel model = Provider.of(context, listen: false);
    await model.refreshData();
  }
}

class _HeaderItemTwoWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    UserTotal userTotal = Provider.of(context, listen: false);
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        RichText(
          text: TextSpan(
            text: '邀请人 ',
            style: TextStyle(fontSize: 13),
            children: [
              TextSpan(
                text: '${userTotal.invitor}',
                style: TextStyle(color: Theme.of(context).accentColor),
              ),
            ],
          ),
        ),
        RichText(
          text: TextSpan(
            text: '用户ID：',
            style: TextStyle(fontSize: 13),
            children: [
              TextSpan(
                text: '${userTotal.userId}',
                style: TextStyle(color: Theme.of(context).accentColor),
              ),
            ],
          ),
        ),
      ],
    );
  }
}

class _HeaderItemThreeWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    UserTotal userTotal = Provider.of(context, listen: false);
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        MineOrderButton(
          name: 'assets/images/mine/ic_pending_pay.png',
          title: '待付款',
          badge: userTotal.total('PAYING_ORDER_TOTAL'),
          onTap: () {
            _onOrderClicked(context, 0);
          },
        ),
        MineOrderButton(
          name: 'assets/images/mine/ic_pending_send.png',
          title: '待发货',
          badge: userTotal.total('SENDING_ORDER_TOTAL'),
          onTap: () {
            _onOrderClicked(context, 1);
          },
        ),
        MineOrderButton(
          name: 'assets/images/mine/ic_pending_receive.png',
          title: '待收货',
          badge: userTotal.total('RECEIPTING_ORDER_TOTAL'),
          onTap: () {
            _onOrderClicked(context, 2);
          },
        ),
        MineOrderButton(
          name: 'assets/images/mine/ic_pending_all.png',
          title: '全部订单',
          onTap: () {
            _onOrderClicked(context, 3);
          },
        ),
      ],
    );
  }

  void _onOrderClicked(BuildContext context, int index) {
    Navigator.of(context).pushNamed('/order', arguments: OrderPageArgs(null, index));
  }
}

class _BottomTitleWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SliverToBoxAdapter(
      child: Container(
        margin: EdgeInsets.only(left: 18, top: 22, right: 18, bottom: 4),
        child: Text(
          '常用功能',
          style: TextStyle(
            color: Colors.black87,
            fontSize: 15,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }
}

class _BottomFuncWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 需要刷新店铺管理
    AppStoreModel appStoreModel = Provider.of(context, listen: false);
    Me me = Provider.of(context, listen: false);
    UserTotal userTotal = Provider.of(context, listen: false);
    return SliverPadding(
      padding: EdgeInsets.symmetric(horizontal: 12),
      sliver: SliverGrid.extent(
        maxCrossAxisExtent: (375 - 24) / 3,
        childAspectRatio: 1.125,
        children: <Widget>[
          MineFuncButton(
            name: 'assets/images/mine/ic_func_score.png',
            title: '我的积分',
            onTap: () => Navigator.of(context).pushNamed('/account', arguments: 'user'),
          ),
          MineFuncButton(
            name: 'assets/images/mine/ic_func_address.png',
            title: '地址管理',
            onTap: () => Navigator.of(context).pushNamed('/address'),
          ),
          // 只有没得店铺 或者 店铺申请审核不成功的时候，才显示申请入口
          if (userTotal.storeId == null || userTotal.storeAuditStatus != 'AUDIT_SUCCESS')
            _ApplyFuncWidget(),
          // 只有有可管理的店铺时，才显示申请入口
          if (appStoreModel.manageableStoreList.isNotEmpty)
            _ManageFuncWidget(),
          _QrcodeFuncWidget(),
          MineFuncButton(
            name: 'assets/images/mine/ic_func_invite.png',
            title: '邀请好友',
            onTap: () => Navigator.of(context).pushNamed('/invite', arguments: me),
          ),
          MineFuncButton(
            name: 'assets/images/mine/ic_func_auth.png',
            title: '实名认证',
            onTap: () => Navigator.of(context).pushNamed('/auth', arguments: me),
          ),
        ],
      ),
    );
  }
}

/// 申请店铺按钮
class _ApplyFuncWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MineFuncButton(
      name: 'assets/images/mine/ic_func_score.png',
      title: '申请店铺',
      onTap: () {
        _onApplyClicked(context);
      },
    );
  }

  /// 点击申请店铺按钮
  void _onApplyClicked(BuildContext context) async {
    // 获取imageFileMap等字段
    UserTotal userTotal = Provider.of(context, listen: false);
    // 转到店铺申请页面
    var result = await Navigator.of(context).pushNamed('/store/apply', arguments: userTotal);
    if (result is StoreApplyQuery) {
      // 添加可管理、切换店铺
      AppStoreModel model = Provider.of(context, listen: false);
      model.manageableStoreList['${result.id}'] = result.storeName;
      model.currentStoreId = result.id;
      // 转到管理页面
      await Navigator.of(context).pushNamed('/store/manage', arguments: result.id);
    }

    // 点了申请店铺页面，最终返回后刷新一下数据。
    MineModel model = Provider.of(context, listen: false);
    await model.refreshData();
  }
}

/// 管理功能按钮
class _ManageFuncWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MineFuncButton(
      name: 'assets/images/mine/ic_func_score.png',
      title: '店铺管理',
      onTap: () {
        _onManageClicked(context);
      },
    );
  }

  /// 点击店铺管理
  /// 单个店铺，直接跳转
  /// 多个店铺，显示列表，再选择具体店铺
  void _onManageClicked(BuildContext context) async {
    AppStoreModel model = Provider.of(context, listen: false);
    final list = model.manageableStoreList.entries.toList();
    if (list.length == 1) {
      // 单个可管理，直接跳转
      var storeId = int.tryParse(list.first.key);
      model.currentStoreId = storeId;
      Navigator.of(context).pushNamed('/store/manage', arguments: storeId);
    } else {
      // 多个可管理，列表选择
      var result = await showModalBottomSheet(
        context: context,
        builder: (context) {
          return _ManageBottomSheetWidget();
        },
      );
      if (result is int) {
        model.currentStoreId = result;
        Navigator.of(context).pushNamed('/store/manage', arguments: result);
      }
    }
  }
}

/// 可管理店铺列表
class _ManageBottomSheetWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    AppStoreModel model = Provider.of(context, listen: false);
    final list = model.manageableStoreList.entries.toList();
    return ListView.builder(
      shrinkWrap: true,
      itemBuilder: (context, index) {
        var mapEntry = list[index];
        return ListTile(
          title: Text(mapEntry.value),
          onTap: () {
            Navigator.of(context).pop(int.tryParse(mapEntry.key));
          },
        );
      },
      itemCount: list.length,
    );
  }
}

/// 扫码注册按钮
class _QrcodeFuncWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => RegNewQrModel(Provider.of(context, listen: false)),
      // 体验好点的话，这里可以添加一个loading的，但暂时不加了。
      child: Builder(
        builder: (context) => MineFuncButton(
          name: 'assets/images/mine/ic_func_scan.png',
          title: '扫码注册',
          onTap: () {
            _onQrcodeClicked(context);
          },
        ),
      ),
    );
  }

  void _onQrcodeClicked(BuildContext context) async {
    var result = await Navigator.of(context).pushNamed('/qrcode');
    if (result == null) {
      return;
    }
    try {
      var uri = Uri.parse(result);
      var queryParameters = uri.queryParameters;
      var encodedClientId = queryParameters['client_id'];
      var invitedCode = queryParameters['ic'];
      if (encodedClientId == null || invitedCode == null) {
        throw '无效二维码';
      }
      RegNewQrModel model = Provider.of(context, listen: false);
      var viewState = await model.regNewQr(encodedClientId, invitedCode);
      switch (viewState) {
        case ViewState.error:
          showToast(model.errorMessage);
          break;
        default:
          showDialog(
            context: context,
            builder: (context) {
              var data = model.data;
              return AlertDialog(
                content: Text('用户名：${data.username}\n密码：${data.originPassword}'),
                actions: <Widget>[
                  FlatButton(
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: Text('确定'),
                  ),
                ],
              );
            },
          );
          break;
      }
    } catch (e) {
      debugPrint('e = $e');
      showToast('无效二维码');
    }
  }
}
